<template>
	<div class="system-add-user-container">
		<el-dialog v-model="dialog" :title="form.id ? '修改用户' : '新增用户'" width="60%" :before-close="handleClose">
			<el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
				<el-row>
					<el-col :span="12" class="mb20">
						<el-form-item label="用户昵称" prop="nikeName">
							<el-input v-model="form.nikeName"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12" class="mb20">
						<el-form-item label="手机号码" prop="phone">
							<el-input v-model="form.phone" maxlength="11" :disabled="form.id" show-word-limit></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12" class="mb20">
						<el-form-item label="用户名" prop="username">
							<el-input v-model="form.username" :disabled="form.id"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12" class="mb20">
						<el-form-item label="密码" prop="password">
							<el-input v-model="form.password" type="password" :disabled="form.id"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12" class="mb20">
						<el-form-item label="部门" prop="deptId">
							<el-tree-select
								style="width: 100%"
								v-model="form.deptId"
								:data="deptList"
								check-strictly
								:props="defaultProps"
								:render-after-expand="false"
								node-key="id"
							></el-tree-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" class="mb20">
						<el-form-item label="状态" prop="status">
							<el-radio-group v-model="form.status">
								<el-radio label="0">禁用</el-radio>
								<el-radio label="1">启用</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="角色权限" prop="roles">
					<el-checkbox-group v-model="form.roles">
						<el-checkbox v-for="(item, index) in roleList" :key="index" :label="item.id">{{ item.roleName }}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="头像" prop="avatar">
					<el-upload
						class="avatar-uploader"
						:action="action"
						:headers="headers"
						:show-file-list="false"
						:before-upload="beforeUpload"
						:on-success="handleSuccess"
						:on-error="handleError"
					>
						<img v-if="form.avatar" :src="form.avatar" class="avatar" />
						<el-icon class="avatar-uploader-icon" v-else> <ele-Plus /> </el-icon>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose">关 闭</el-button>
					<el-button type="primary" :loading="loading" @click="submitForm(formRef)">确 认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRefs } from 'vue';
import { addObj, editObj, getById } from '/@/api/upms/sysuser';
import { getList as getRoleList } from '/@/api/upms/sysrole';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Session } from '/@/utils/storage';
import type { UploadProps } from 'element-plus';
interface UserSate {
	rules: object;
	form: {
		id: undefined;
		password: string;
		deptId: string;
		username: string;
		phone: string;
		nikeName: string;
		avatar: string;
		enableFlag: string;
		roles: Array<string>;
	};
	roleList: any;
	deptList: any;
}

export default defineComponent({
	emits: ['initPage'],
	setup(props, { emit }) {
		const data = reactive<UserSate>({
			form: {
				id: undefined,
				password: '',
				deptId: '',
				username: '',
				phone: '',
				nikeName: '',
				avatar: '',
				enableFlag: '1',
				roles: [],
			},
			rules: {
				nikeName: [
					{
						required: true,
						message: '请输入用户昵称',
						trigger: 'change',
					},
				],
				phone: [
					{
						required: true,
						message: '请输入手机号码',
						trigger: 'change',
					},
				],
				username: [
					{
						required: true,
						message: '请输入用户名',
						trigger: 'change',
					},
				],
				password: [
					{
						required: true,
						message: '请输入密码',
						trigger: 'change',
					},
				],
				enableFlag: [
					{
						required: true,
						message: '请选择状态',
						trigger: 'change',
					},
				],
				roles: [
					{
						required: true,
						message: '请选择角色',
						trigger: 'change',
					},
				],
				deptId: [
					{
						required: true,
						message: '请选择部门',
						trigger: 'change',
					},
				],
				avatarArray: [
					{
						required: true,
						message: '请上传头像',
						trigger: 'change',
					},
				],
			},
			roleList: [],
			deptList: [],
		});
		const dialog = ref(false);
		const loading = ref(false);
		const formRef = ref();
		const headers = {
			satoken: Session.get('token'),
		};
		const action = '/upms/file/upload?fileType=image';
		const { form, rules, roleList, deptList } = toRefs(data);
		const defaultProps = {
			children: 'children',
			label: 'name',
		};
		const initForm = (row: any | undefined) => {
			dialog.value = true;
			if (row && row.id) {
				getDetail(row.id);
			}

			handleRoleList();
		};
		const getDetail = (id: string) => {
			loading.value = true;
			getById(id).then((response: any) => {
				data.form = response.data.data;
				loading.value = false;
			});
		};
		/**
		 * 关闭事件
		 */
		const handleClose = () => {
			resetForm(formRef.value);
		};
		/**
		 * 重置表单
		 */
		const resetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			data.form.id = undefined;
			loading.value = false;
			dialog.value = false;
			formEl.resetFields();
		};
		/**
		 * 提交按钮
		 */
		const submitForm = async (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			await formEl.validate((valid, fields) => {
				if (valid) {
					loading.value = true;
					if (data.form.id) {
						//修改
						edit();
					} else {
						//新增
						add();
					}
				}
			});
		};
		/**
		 * 新增
		 */
		const add = () => {
			addObj(form.value)
				.then((response: any) => {
					resetForm(formRef.value);
					ElMessage.success('新增成功');

					emit('initPage');
				})
				.catch(() => {
					loading.value = false;
				});
		};
		/**
		 * 修改
		 */
		const edit = () => {
			editObj(form.value)
				.then((response: any) => {
					resetForm(formRef.value);
					ElMessage.success('修改成功');
					emit('initPage');
				})
				.catch(() => {
					loading.value = false;
				});
		};
		/**
		 * 查询全部角色
		 */
		const handleRoleList = () => {
			getRoleList({}).then((response: any) => {
				roleList.value = response.data.data;
			});
		};
		/**
		 * 上传前
		 */
		const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
			if (rawFile.type !== 'image/jpeg') {
				ElMessage.error('Avatar picture must be JPG format!');
				return false;
			} else if (rawFile.size / 1024 / 1024 > 2) {
				ElMessage.error('Avatar picture size can not exceed 2MB!');
				return false;
			}
			return true;
		};
		/**
		 * 上传成功事件
		 */
		const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
			form.value.avatar = response.data;
		};
		/**
		 * 上传失败事件
		 */
		const handleError: UploadProps['onError'] = (error) => {
			ElMessage.error(error + '');
		};
		return {
			form,
			rules,
			action,
			dialog,
			headers,
			loading,
			formRef,
			roleList,
			deptList,
			defaultProps,
			initForm,
			handleClose,
			submitForm,
			handleRoleList,
			beforeUpload,
			handleSuccess,
			handleError,
		};
	},
});
</script>
<style scoped>
.avatar-uploader .avatar {
	width: 140px;
	height: 140px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 26px;
	color: #8c939d;
	width: 140px;
	height: 140px;
	text-align: center;
}
</style>
